package com.banyou.banyou.main.setting;

import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.banyou.banyou.R;
import com.banyou.banyou.adapter.PicUriAdapter;
import com.banyou.banyou.base.BaseActivity;
import com.banyou.banyou.bean.main.setting.NewSettingBean;
import com.banyou.banyou.bean.main.setting.SettingBean;
import com.banyou.banyou.customviews.ScrollGridView;
import com.banyou.banyou.util.DialogFactory;
import com.banyou.banyou.util.FontDisplayUtil;
import com.banyou.banyou.util.GlideUtil;
import com.banyou.banyou.util.ShowAddressPicker;
import com.banyou.banyou.util.ShowToast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;
import cn.qqtheme.framework.picker.NumberPicker;
import cn.qqtheme.framework.picker.OptionPicker;

/**
 * ----------Dragon be here!----------/
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃代码无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * 类描述：
 * 创建人：Random
 * 修改时间：
 * 修改备注：
 */

public class SettingActivity extends BaseActivity<SettingPresenter> implements SettingContract.View {

    @BindView(R.id.back_btn)
    ImageView mBackBtn;
    @BindView(R.id.title_bar)
    RelativeLayout mTitleBar;
    @BindView(R.id.head_img)
    ImageView mHeadImg;
    @BindView(R.id.header_content)
    LinearLayout mHeaderContent;
    @BindView(R.id.add_photo)
    TextView mAddPhoto;
    @BindView(R.id.scroll_grid)
    ScrollGridView mScrollGrid;
    @BindView(R.id.new_name)
    TextView mNewName;
    @BindView(R.id.new_password)
    TextView mNewPassword;
    @BindView(R.id.new_mysign)
    TextView mNewMysign;
    @BindView(R.id.change_btn)
    Button mChangeBtn;
    @BindView(R.id.new_age)
    TextView mNewAge;
    @BindView(R.id.new_city)
    TextView mNewCity;
    private final int HEAD_CHANGE = 0x11, IMAGE_CHANGE = 0x22, NAME_CHANGE = 0x33, PASSWORD_CHANGE = 0x44, USERSIGN_CHANGE = 0x55, BODY_HEIGHT = 0x66, BODY_WEIGHT = 0x77, MARRIAGE = 0x88, WORK = 0x99, STU = 0x100;
    @BindView(R.id.body_height)
    TextView mNewBodyHeight;
    @BindView(R.id.body_weight)
    TextView mNewBodyWeight;
    @BindView(R.id.marriage)
    TextView mNewMarriage;
    @BindView(R.id.work)
    TextView mNewWork;
    @BindView(R.id.stu)
    TextView mNewStu;
    @BindView(R.id.language)
    TextView mNewLanguage;
    @BindView(R.id.star)
    TextView mNewStar;
    @BindView(R.id.new_sex)
    TextView mNewSex;

    private String mUserSign, mBodyWeight, mBodyHeight, mWork, mStu;
    private PicUriAdapter mAdapter;
    private List<String> mUriList;
    private int mAge;
    private String mOldPassword, mPassword, mName;
    private String mSex;
    private NewSettingBean mInfo=new NewSettingBean();
    private String mCityCode,mStar,mLanguage;
    private String mHeadImage;
    private String mMarriage;
    @Override
    protected SettingPresenter initPresenter() {
        return new SettingPresenter();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_setting;
    }

    @Override
    protected View initLayoutView() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter.initPresenter(this, new SettingModel());
        ButterKnife.bind(this);
        mUriList = new ArrayList<>();
        mAdapter = new PicUriAdapter(mUriList, this);
        mScrollGrid.setAdapter(mAdapter);
        mInfo.setAttributes(new NewSettingBean.AttributesBean());

        mInfo.setUserId(Integer.parseInt(getSharedPreference().getString("userId","")));
        mInfo.getAttributes().setUSER_PHOTO_ALUM("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1496483147435&di=6e840ede38ed32e9f621a086b3d6f69b&imgtype=0&src=http%3A%2F%2Fimage.tianjimedia.com%2FuploadImages%2F2015%2F204%2F22%2FYMG9CAUWUM15.jpg,https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1496483147435&di=0fe575bafedad25a549dd52dd6abc7ce&imgtype=0&src=http%3A%2F%2Fimage.tianjimedia.com%2FuploadImages%2F2015%2F204%2F21%2F9OF916367T7P.jpg,https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1496483147435&di=cf19a47c02e6e6a5a8383415dca64502&imgtype=0&src=http%3A%2F%2Fimage.tianjimedia.com%2FuploadImages%2F2015%2F204%2F24%2FQ3NSQD2094FO.jpg");
        if(getSharedPreference().getString("userType","").equals("1")){
            mAddPhoto.setVisibility(View.GONE);
        }

    }

    @Override
    protected String pageName() {
        return "设置页面";
    }

    @OnClick({R.id.back_btn, R.id.head_img, R.id.add_photo, R.id.new_name, R.id.new_password, R.id.new_mysign, R.id.change_btn, R.id.new_age, R.id.body_height, R.id.body_weight, R.id.marriage, R.id.work, R.id.stu,R.id.new_city,R.id.star,R.id.language,R.id.new_sex})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                SettingActivity.this.finish();
                break;
            case R.id.head_img:
                createDialog(HEAD_CHANGE);
                break;
            case R.id.add_photo:
                GalleryFinal.openGalleryMuti(IMAGE_CHANGE, 9, mCallBack);
                break;
            case R.id.new_name:
                createOneEditDialog(NAME_CHANGE);
                break;
            case R.id.new_password:
                createTwoEditDialog();
                break;
            case R.id.new_mysign:
                createOneEditDialog(USERSIGN_CHANGE);
                break;
            case R.id.new_age:
                NumberPicker picker = new NumberPicker(this);
                picker.setItemWidth(200);
                picker.setCycleDisable(false);
                picker.setCanceledOnTouchOutside(true);
                picker.setOffset(5);//偏移量
                picker.setRange(10, 90, 1);//数字范围
                picker.setSelectedItem(18);
                picker.setLabel("岁");
                picker.setCancelable(true);
                picker.setOnNumberPickListener(mPickListener);
                picker.show();
                break;
            case R.id.change_btn:
                mPresenter.changeSetting(JSON.toJSONString(mInfo));
                break;
            case R.id.body_height:
                createOneEditDialog(BODY_HEIGHT);
                break;
            case R.id.body_weight:
                createOneEditDialog(BODY_WEIGHT);
                break;
            case R.id.marriage:
                OptionPicker picker1 = new OptionPicker(this, new String[]{"已婚", "未婚"});
                picker1.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
                    @Override
                    public void onOptionPicked(int index, String item) {
                        mNewMarriage.setText("婚姻修改为："+item);
                        mNewMarriage.setTextColor(getResources().getColor(R.color.orange_ff9933));
                        mMarriage=item;
                        mInfo.getAttributes().setUSER_MARRAGE(mMarriage);

                    }
                });
                picker1.show();
                break;
            case R.id.work:
                createOneEditDialog(WORK);
                break;
            case R.id.stu:
                createOneEditDialog(STU);
                break;
            case R.id.new_city:
                ShowAddressPicker.show(this, new ShowAddressPicker.OnCityPickedCallBack() {
                    @Override
                    public void onAddressPicked(Province province, City city, County county) {
                        mNewCity.setText("你的位置：" + province.getName() + "-" + city.getName());
                        mNewCity.setTextColor(getResources().getColor(R.color.orange_ff9933));
                        mCityCode=(String)city.getId();
                        mInfo.setRegionId(mCityCode);
                    }
                });
                break;
            case R.id.language:
                OptionPicker picker2 = new OptionPicker(this, new String[]{"汉语", "英语","日语"});
                picker2.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
                    @Override
                    public void onOptionPicked(int index, String item) {
                        mLanguage=item;
                        mNewLanguage.setText("语言修改为："+mLanguage);
                        mNewLanguage.setTextColor(getResources().getColor(R.color.orange_ff9933));
                        mInfo.getAttributes().setUSER_LANGUAGE(mLanguage);

                    }
                });
                picker2.show();
                break;
            case R.id.star:
                OptionPicker picker3 = new OptionPicker(this, new String[]{"白羊座", "金牛座","双子座","巨蟹座","狮子座","处女座","天秤座","天蝎座","射手座","摩羯座","水瓶座","双鱼座"});
                picker3.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
                    @Override
                    public void onOptionPicked(int index, String item) {
                        mStar=item;
                        mNewStar.setText("星座修改为："+mStar);
                        mNewStar.setTextColor(getResources().getColor(R.color.orange_ff9933));
                        mInfo.getAttributes().setUSER_STAR(mStar);

                    }
                });
                picker3.show();
                break;
            case R.id.new_sex:
                OptionPicker picker4 = new OptionPicker(this, new String[]{"男","女"});
                picker4.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
                    @Override
                    public void onOptionPicked(int index, String item) {
                        if(index==0){
                            mSex="M";
                        }else{
                            mSex="F";
                        }
                        mNewSex.setText("性别修改为："+item);
                        mNewSex.setTextColor(getResources().getColor(R.color.orange_ff9933));
                    }
                });
                picker4.show();
                break;
        }
    }

    private NumberPicker.OnNumberPickListener mPickListener = new NumberPicker.OnNumberPickListener() {
        @Override
        public void onNumberPicked(int index, Number item) {
            int i = item.intValue();
            mNewAge.setText("修改年龄\t\t\t\t已选择：" + i + "岁");
            mNewAge.setTextColor(getResources().getColor(R.color.orange_ff9933));
            mAge = i;
            mInfo.getAttributes().setAGE(mAge+"");
        }
    };


    /**
     * 创建一个有两个EditText的Dialog
     */
    private void createTwoEditDialog() {
        final EditText oldEdit = new EditText(this);
        final EditText newEdit = new EditText(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, FontDisplayUtil.dip2px(40));
        params.setMargins(0, 0, 0, FontDisplayUtil.dip2px(10));
        oldEdit.setLayoutParams(params);
        newEdit.setLayoutParams(params);
        oldEdit.setMaxLines(1);
        newEdit.setMaxLines(1);
        oldEdit.setHint("输入新密码");
        newEdit.setHint("再次输入新密码");
        DialogFactory factory = new DialogFactory(this);
        factory.setCancleAble(true);
        mPasswordDialog = factory.createDialog("修改密码");
        factory.setOneButton(true);
        factory.setSureBtnText("确定修改");
        factory.setView(oldEdit);
        factory.setView(newEdit);
        factory.setOnBtnClickListener(new DialogFactory.OnBtnClickListener() {
            @Override
            public void onSureClick(View view) {
                if (oldEdit.getText().toString().trim().length() != 0 && newEdit.getText().toString().trim().length() != 0) {
                    mPasswordDialog.dismiss();
                    mOldPassword = oldEdit.getText().toString();
                    mPassword = newEdit.getText().toString();
                    Map<String,String> map=new HashMap<>();
                    map.put("userId",getSharedPreference().getString("userId",""));
                    map.put("confirmPassword",mPassword);
                    map.put("newPassword",mOldPassword);
                    mPresenter.changePassword(map);
                } else {
                    Toast.makeText(SettingActivity.this, "请输入全部内容", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onCancleClick(View view) {

            }
        });
        mPasswordDialog.show();
    }

    private AlertDialog mNameDialog, mPasswordDialog;

    /**
     * 创建一个只有一个EditText的Dialog
     */
    private void createOneEditDialog(final int code) {
        final EditText edit = new EditText(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, FontDisplayUtil.dip2px(40));
        params.setMargins(0, 0, 0, FontDisplayUtil.dip2px(10));
        edit.setLayoutParams(params);
        edit.setMaxLines(1);
        DialogFactory factory = new DialogFactory(this);
        factory.setCancleAble(true);
        String str = "";
        switch (code) {
            case NAME_CHANGE:
                str = "输入要修改的名字";
                break;
            case USERSIGN_CHANGE:
                str = "输入要修改的个人介绍";
                break;
            case BODY_HEIGHT:
                str = "输入要修改的身高（cm）";
                break;
            case BODY_WEIGHT:
                str = "输入要修改的体重（kg）";
                break;
            case WORK:
                str = "输入要修改的工作";
                break;
            case STU:
                str = "输入要修改的毕业院校";
                break;
        }
        edit.setHint(str);
        mNameDialog = factory.createDialog(str);
        factory.setOneButton(true);
        factory.setSureBtnText("确定修改");
        factory.setView(edit);
        factory.setOnBtnClickListener(new DialogFactory.OnBtnClickListener() {
            @Override
            public void onSureClick(View view) {
                if (edit.getText().toString().trim().length() != 0) {
                    mNameDialog.dismiss();
                    String s = edit.getText().toString();
                    switch (code) {
                        case NAME_CHANGE:
                            mName = s;
                            mNewName.setText("姓名修改为：" + mName);
                            mNewName.setTextColor(getResources().getColor(R.color.orange_ff9933));
                            mInfo.setUserName(mName);
                            break;
                        case USERSIGN_CHANGE:
                            mUserSign = s;
                            mNewMysign.setText("签名修改为：" + mUserSign);
                            mNewMysign.setTextColor(getResources().getColor(R.color.orange_ff9933));
                            mInfo.setRemarks(mUserSign);
                            break;
                        case BODY_HEIGHT:
                            mBodyHeight = s;
                            mNewBodyHeight.setText("身高修改为："+mBodyHeight+"cm");
                            mNewBodyHeight.setTextColor(getResources().getColor(R.color.orange_ff9933));
                            mInfo.getAttributes().setUSER_HEIGHT(mBodyHeight);

                            break;
                        case BODY_WEIGHT:
                            mBodyWeight = s;
                            mNewBodyWeight.setText("体重修改为："+mBodyWeight+"kg");
                            mNewBodyWeight.setTextColor(getResources().getColor(R.color.orange_ff9933));
                            mInfo.getAttributes().setUSER_WEIGHT(mBodyWeight);

                            break;
                        case WORK:
                            mWork = s;
                            mNewWork.setText("工作修改为："+mWork);
                            mNewWork.setTextColor(getResources().getColor(R.color.orange_ff9933));
                            mInfo.getAttributes().setUSER_JOB(mWork);

                            break;
                        case STU:
                            mStu = s;
                            mNewStu.setText("学历修改为："+mStu);
                            mNewStu.setTextColor(getResources().getColor(R.color.orange_ff9933));
                            mInfo.getAttributes().setUSER_DEGREE(mStu);

                            break;
                    }
                } else {
                    Toast.makeText(SettingActivity.this, "请输入文字", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onCancleClick(View view) {

            }
        });
        mNameDialog.show();
    }

    private AlertDialog mDialog;
    private GalleryFinal.OnHanlderResultCallback mCallBack = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            switch (reqeustCode) {
                case HEAD_CHANGE:
                    GlideUtil.circleLocalLoad(SettingActivity.this, resultList.get(0).getPhotoPath(), mHeadImg);
                    break;
                case IMAGE_CHANGE:
                    mUriList.clear();
                    for (int i = 0; i < resultList.size(); i++) {
                        mUriList.add(resultList.get(i).getPhotoPath());
                    }
                    mAdapter.notifyDataSetChanged();
                    break;
            }
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {

        }
    };

    /**
     * 创建dialog
     */
    private void createDialog(final int code) {
        View view = LayoutInflater.from(this).inflate(R.layout.chose_pictor_dialog, null);
        ViewHolder holder = new ViewHolder(view);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        mDialog = builder.setView(view)
                .setTitle("请选择类型")
                .setMessage("使用相册上传，或者拍摄一张新照片")
                .create();
        //使用相机监听
        holder.mCameraBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                GalleryFinal.openCamera(code, mCallBack);
            }
        });
        //使用相册监听
        holder.mChooseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                GalleryFinal.openGallerySingle(code, mCallBack);
            }
        });
        mDialog.show();
    }

    /**
     * 改变Setting成功
     */
    @Override
    public void changeSettingSuccess() {
        ShowToast.showToast("设置成功");
    }

    /**
     * 改变Setting失败
     */
    @Override
    public void changeSettingFail() {
        ShowToast.showToast("设置失败");
    }

    /**
     * 修改密码成功
     */
    @Override
    public void changePasswordSuccess() {
        ShowToast.showToast("密码修改成功！");
        mNewPassword.setText("设置新密码成功");
        mNewPassword.setTextColor(getResources().getColor(R.color.orange_ff9933));
    }


    static class ViewHolder {
        @BindView(R.id.choose_btn)
        Button mChooseBtn;
        @BindView(R.id.camera_btn)
        Button mCameraBtn;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
